import * as cornerstone from 'cornerstone-core';
import * as cornerstoneTools from 'cornerstone-tools';

class ROIUtils {
  constructor() {
    this.activeTool = null;
    this.roiElements = new Map(); // 存储所有ROI元素
    this.contextMenu = null;
    this.selectedROI = null;
  }

  // 初始化ROI工具
  initialize() {
    console.log('版本',cornerstoneTools.version);
    const EllipticalRoiTool = cornerstoneTools.EllipticalRoiTool;

    
    // 注册椭圆ROI工具
    cornerstoneTools.addTool(EllipticalRoiTool, {
      configuration: {
        shadow: true,
        preventHandleOutsideImage: true,
         handleRadius:0.01
      },
    });
   
    // 颜色定制代码
    // cornerstoneTools.textStyle.setBackgroundColor("red");
    // cornerstoneTools.textStyle.setFontSize(12);
    // cornerstoneTools.textStyle.setFontFamily('Microsoft JhengHei');
    // cornerstoneTools.toolColors.setActiveColor("red");
    // cornerstoneTools.toolColors.setFillColor('red');
    // cornerstoneTools.toolColors.setToolColor("red");


    
   
  }

  


  // 查找点击位置的ROI
  findROIAtPosition(roiData, event) {
    const element = event.target;
    
    // 检查元素是否已启用cornerstone
    let enabledElement = null;
    try {
      enabledElement = cornerstone.getEnabledElement(element);
    } catch (error) {
      console.warn('获取enabled element失败:', error.message);
      return null;
    }
    
    if (!enabledElement) {
      console.log('元素未启用cornerstone，无法查找ROI');
      return null;
    }

    if (!enabledElement.image) {
      console.log('元素没有图像数据，无法查找ROI');
      return null;
    }

    const image = enabledElement.image;
    const rect = element.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    for (const roi of roiData) {
      if (this.isPointInROI(roi, x, y, image)) {
        return roi;
      }
    }
    return null;
  }

  // 判断点是否在ROI内
  isPointInROI(roi, x, y, image) {
    if (roi.toolType === 'EllipticalRoi') {
      return this.isPointInEllipse(roi, x, y, image);
    } 
    return false;
  }

  // 判断点是否在椭圆内
  isPointInEllipse(roi, x, y, image) {
    const { start, end } = roi.handles;
    const centerX = (start.x + end.x) / 2;
    const centerY = (start.y + end.y) / 2;
    const radiusX = Math.abs(end.x - start.x) / 2;
    const radiusY = Math.abs(end.y - start.y) / 2;

    const normalizedX = (x - centerX) / radiusX;
    const normalizedY = (y - centerY) / radiusY;

    return (normalizedX * normalizedX + normalizedY * normalizedY) <= 1;
  }

  // 判断点是否在多边形内
  isPointInPolygon(roi, x, y, image) {
    const points = roi.points;
    let inside = false;
    
    for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
      const xi = points[i].x, yi = points[i].y;
      const xj = points[j].x, yj = points[j].y;
      
      const intersect = ((yi > y) !== (yj > y))
          && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }
    
    return inside;
  }

  // 显示右键菜单
  showContextMenu(event) {
    this.contextMenu.style.display = 'block';
    this.contextMenu.style.left = `${event.clientX}px`;
    this.contextMenu.style.top = `${event.clientY}px`;
  }

  // 隐藏右键菜单
  hideContextMenu() {
    this.contextMenu.style.display = 'none';
    this.selectedROI = null;
  }


  // 激活椭圆ROI工具
  activateEllipseROI() {
    const element = document.querySelector('.viewport.active canvas') || 
                   document.querySelector('.viewport canvas');
    if (!element) return;

    // 停用其他工具
    cornerstoneTools.setToolActive('Pan', { mouseButtonMask: 0 });
    cornerstoneTools.setToolActive('Zoom', { mouseButtonMask: 0 });
    cornerstoneTools.setToolActive('Wwwc', { mouseButtonMask: 0 });
 

    // 重新配置椭圆ROI工具
    cornerstoneTools.setToolActive('EllipticalRoi', {
      mouseButtonMask: 1,
      preventHandleOutsideImage: true,
      supportedInteractionTypes: ['Mouse', 'Touch'],
    
    });

    this.activeTool = 'EllipticalRoi';
  }


  // 清除所有ROI
//   clearAllROIs() {
//     console.log('准备清空所有视口的ROI标记');
    
//     // 获取所有激活的视口元素
//     const enabledElements = cornerstone.getEnabledElements();
    
//     // 遍历所有视口并清空EllipticalRoi标记
//     enabledElements.forEach(element => {
//         if (element.viewport) {
//             cornerstoneTools.clearToolState(element.element, 'EllipticalRoi');
//             cornerstone.updateImage(element.element);
//         }
//     });
    
//     console.log('已清空所有视口的ROI标记');
// }
  // clearAllROIs(viewport) {
    

  //   // 清除椭圆ROI
  //   // const ellipseToolState = cornerstoneTools.getToolState(element, 'EllipticalRoi');
  //   // if (ellipseToolState) {
  //   //   ellipseToolState.data = [];
  //   // }
    
  //   console.log('当前是啥',viewport);
    
  //   cornerstoneTools.clearToolState(viewport, 'EllipticalRoi');
  //   cornerstoneTools.updateImage(viewport)

 

  // }

  // 获取ROI统计信息
  getROIStats(roi) {
    if (!roi) return null;

    const stats = {
      area: 0,
      perimeter: 0,
      mean: 0,
      stdDev: 0,
    };

    const element = document.querySelector('.viewport.active canvas') || 
                   document.querySelector('.viewport canvas');
    if (!element) return stats;

    // 检查元素是否已启用cornerstone
    let enabledElement = null;
    try {
      enabledElement = cornerstone.getEnabledElement(element);
    } catch (error) {
      console.warn('获取enabled element失败:', error.message);
      return stats;
    }
    
    if (!enabledElement) {
      console.log('元素未启用cornerstone，返回默认统计信息');
      return stats;
    }

    if (!enabledElement.image) {
      console.log('元素没有图像数据，返回默认统计信息');
      return stats;
    }

    // 计算ROI的统计信息
    if (roi.toolType === 'EllipticalRoi') {
      stats.area = this.calculateEllipseArea(roi);
      stats.perimeter = this.calculateEllipsePerimeter(roi);
    } 

    // 计算像素统计信息
    const pixelStats = this.calculatePixelStats(roi, enabledElement.image);
    stats.mean = pixelStats.mean;
    stats.stdDev = pixelStats.stdDev;

    return stats;
  }

  // 计算椭圆面积
  calculateEllipseArea(roi) {
    const { start, end } = roi.handles;
    const radiusX = Math.abs(end.x - start.x) / 2;
    const radiusY = Math.abs(end.y - start.y) / 2;
    return Math.PI * radiusX * radiusY;
  }

  // 计算椭圆周长
  calculateEllipsePerimeter(roi) {
    const { start, end } = roi.handles;
    const radiusX = Math.abs(end.x - start.x) / 2;
    const radiusY = Math.abs(end.y - start.y) / 2;
    // 使用Ramanujan近似公式
    const h = Math.pow(radiusX - radiusY, 2) / Math.pow(radiusX + radiusY, 2);
    return Math.PI * (radiusX + radiusY) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));
  }

  // 计算多边形面积
  calculatePolygonArea(roi) {
    const points = roi.points;
    let area = 0;
    for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
      area += (points[j].x + points[i].x) * (points[j].y - points[i].y);
    }
    return Math.abs(area / 2);
  }

  // 计算多边形周长
  calculatePolygonPerimeter(roi) {
    const points = roi.points;
    let perimeter = 0;
    for (let i = 0; i < points.length; i++) {
      const j = (i + 1) % points.length;
      const dx = points[j].x - points[i].x;
      const dy = points[j].y - points[i].y;
      perimeter += Math.sqrt(dx * dx + dy * dy);
    }
    return perimeter;
  }

  // 计算像素统计信息
  calculatePixelStats(roi, image) {
    const stats = {
      mean: 0,
      stdDev: 0,
    };

    if (!image || !image.getPixelData) return stats;

    const pixelData = image.getPixelData();
    const width = image.width;
    const height = image.height;

    let sum = 0;
    let sumSquared = 0;
    let count = 0;

    // 遍历ROI内的像素
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        if (this.isPointInROI(roi, x, y, image)) {
          const pixelValue = pixelData[y * width + x];
          sum += pixelValue;
          sumSquared += pixelValue * pixelValue;
          count++;
        }
      }
    }

    if (count > 0) {
      stats.mean = sum / count;
      stats.stdDev = Math.sqrt((sumSquared / count) - (stats.mean * stats.mean));
    }

    return stats;
  }
}

export default new ROIUtils(); 